#!/bin/bash

# Debug script to diagnose MCP server startup issues
echo "=== STRUCTURAL TEXT ANALYZER - DEBUG STARTUP ==="
echo "Timestamp: $(date)"
echo "Working directory: $(pwd)"
echo "Script location: $(dirname "$0")"
echo

# Check basic requirements
echo "1. Checking Python availability..."
if command -v python3 >/dev/null 2>&1; then
    echo "✓ Python3 found: $(python3 --version)"
else
    echo "✗ Python3 not found!"
    exit 1
fi

echo

# Check directory structure
echo "2. Checking directory structure..."
cd "$(dirname "$0")"
echo "Current directory: $(pwd)"

if [ -f "server.py" ]; then
    echo "✓ server.py found"
else
    echo "✗ server.py not found!"
    exit 1
fi

if [ -f "analyzer.py" ]; then
    echo "✓ analyzer.py found"
else
    echo "✗ analyzer.py not found!"
    exit 1
fi

echo

# Check basic Python imports
echo "3. Checking core Python imports..."
python3 -c "
import sys
print(f'Python version: {sys.version}')
print(f'Python path: {sys.path[:3]}...')

try:
    import numpy
    print('✓ numpy available')
except ImportError as e:
    print(f'✗ numpy missing: {e}')

try:
    import pandas  
    print('✓ pandas available')
except ImportError as e:
    print(f'✗ pandas missing: {e}')

try:
    import scipy
    print('✓ scipy available')
except ImportError as e:
    print(f'✗ scipy missing: {e}')
"

echo

# Test analyzer import
echo "4. Testing analyzer import..."
export PYTHONPATH="$(pwd):$PYTHONPATH"
python3 -c "
import sys
sys.path.insert(0, '.')

try:
    # Fix relative imports by modifying analyzer.py temporarily
    import importlib.util
    spec = importlib.util.spec_from_file_location('config', './config.py')
    config_module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(config_module)
    
    # Add to sys.modules to make it importable
    sys.modules['config'] = config_module
    
    print('✓ Config module loaded successfully')
    
    # Now try to import analyzer components
    from modules.text_analyzer import TextAnalyzer
    from modules.numerical_analyzer import NumericalAnalyzer
    print('✓ Analysis modules loaded successfully')
    
except Exception as e:
    print(f'✗ Analyzer import failed: {e}')
    import traceback
    traceback.print_exc()
"

echo

# Test basic MCP server dependencies
echo "5. Testing MCP dependencies..."
python3 -c "
try:
    from fastmcp import FastMCP
    print('✓ FastMCP available')
except ImportError as e:
    print(f'✗ FastMCP missing: {e}')
    print('  This is expected and will be installed automatically')

try:
    from dotenv import load_dotenv
    print('✓ python-dotenv available')
except ImportError as e:
    print(f'✗ python-dotenv missing: {e}')
    print('  This will be installed automatically')
"

echo

# Check virtual environment status
echo "6. Checking virtual environment..."
if [ -d ".venv" ]; then
    echo "✓ Virtual environment exists at .venv"
    echo "  Activation test:"
    if [ -f ".venv/bin/python" ]; then
        echo "  ✓ Python executable found in venv"
        .venv/bin/python --version
    else
        echo "  ✗ Python executable not found in venv"
    fi
else
    echo "⚠ No virtual environment found (will be created on first run)"
fi

echo

# Check uv availability
echo "7. Checking uv package manager..."
if command -v uv >/dev/null 2>&1; then
    echo "✓ uv found: $(uv --version)"
else
    echo "⚠ uv not found (will use pip fallback)"
fi

echo

# Test run.sh script permissions and basic execution
echo "8. Testing run.sh script..."
if [ -f "run.sh" ]; then
    echo "✓ run.sh exists"
    
    if [ -x "run.sh" ]; then
        echo "✓ run.sh is executable"
    else
        echo "✗ run.sh is not executable"
        echo "  Run: chmod +x run.sh"
    fi
    
    echo "run.sh content preview:"
    head -10 run.sh | sed 's/^/  /'
else
    echo "✗ run.sh not found!"
fi

echo

echo "9. Environment variables check..."
if [ -f ".env" ]; then
    echo "✓ .env file found"
    echo ".env content:"
    cat .env | sed 's/^/  /'
else
    echo "⚠ No .env file (using defaults)"
fi

echo
echo "=== DEBUG COMPLETE ==="
echo
echo "Next steps:"
echo "1. If any ✗ errors above, fix them first"
echo "2. Make sure run.sh is executable: chmod +x run.sh"
echo "3. Try manual server start: ./run.sh"
echo "4. Check Claude MCP connection again"
